package com.cml.getway.core.netty.processor.filter.pre;

import com.cml.getway.common.config.DubboServiceInvoker;
import com.cml.getway.common.config.Rule;
import com.cml.getway.common.constants.GetwayProtocol;
import com.cml.getway.common.constants.ProcessorFilterConstants;
import com.cml.getway.core.context.AttributeKey;
import com.cml.getway.core.context.Context;
import com.cml.getway.core.context.GetwayContext;
import com.cml.getway.core.context.GetwayRequest;
import com.cml.getway.core.netty.processor.filter.AbstractEntryProcessorFilter;
import com.cml.getway.core.netty.processor.filter.Filter;
import com.cml.getway.core.netty.processor.filter.ProcessorFilterType;
import lombok.Getter;
import lombok.Setter;


@Filter(
		id = ProcessorFilterConstants.TIMEOUT_PRE_FILTER_ID,
		name = ProcessorFilterConstants.TIMEOUT_PRE_FILTER_NAME,
		value = ProcessorFilterType.PRE,
		order = ProcessorFilterConstants.TIMEOUT_PRE_FILTER_ORDER
		)
public class TimeoutPreFilter extends AbstractEntryProcessorFilter<TimeoutPreFilter.Config> {

	public TimeoutPreFilter() {
		super(Config.class);
	}
	

	@Override
	public void entry(Context ctx, Object... args) throws Throwable {
		try {
			GetwayContext getwayContext = (GetwayContext)ctx;
			String protocol = getwayContext.getProtocol();
			Config config = (Config) args[0];
			switch (protocol) {
				case GetwayProtocol.HTTP:
					GetwayRequest rapidRequest = getwayContext.getRequest();
					rapidRequest.setRequestTimeout(config.getTimeout());
					break;
				case GetwayProtocol.DUBBO:
					DubboServiceInvoker dubboServiceInvoker = (DubboServiceInvoker)getwayContext.getRequiredAttribute(AttributeKey.DUBBO_INVOKER);
					dubboServiceInvoker.setTimeout(config.getTimeout());
					break;
				default:
					break;
			}			
		} finally {
			//	非常重要的，一定要记得：驱动我们的过滤器链表
			super.fireNext(ctx, args);
		}
	}
	
	@Getter
	@Setter
	public static class Config extends Rule.FilterConfig {
		private Integer timeout;
	}
	
}
